package com.atguigu.ucenterservice.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.ucenterservice.entity.UcenterMember;
import com.atguigu.ucenterservice.entity.vo.RegisterVo;
import com.atguigu.ucenterservice.service.UcenterMemberService;
import io.jsonwebtoken.ExpiredJwtException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author 陈烨庆
 * @since 2022-04-06
 */
@RestController
@Api("登录")
@RequestMapping("/edumember/apimember")
@CrossOrigin
public class UcenterMemberController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody UcenterMember ucenterMember) {
        // 调用 service 方法实现登录
        // 返回 token 值，使用 jwt 生成
        String token = ucenterMemberService.login(ucenterMember);

        return R.ok().data("token", token);
    }

    /**
     * 注册
     *
     * @param registerVo 注册内容
     * @return
     */
    @PostMapping("register")
    public R register(@RequestBody RegisterVo registerVo) {
        R register = ucenterMemberService.register(registerVo);

        return register;
    }

    /**
     * 根据 token 获取用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("getMemberInfo")
    public R getMemberInfo(HttpServletRequest request) {
        String memberId = null;
        try {
            memberId = JwtUtils.getMemberIdByJwtToken(request);
        } catch (ExpiredJwtException e) {
            throw new GuliException(20001, "token已过期");
        }
        UcenterMember member = ucenterMemberService.getById(memberId);
        return R.ok().data("userInfo", member);
    }


}

